//
//  IPHelper.m
//  edu24app
//
//  Created by BobO on 16/1/20.
//  Copyright © 2016年 edu24ol. All rights reserved.
//

#import "IPHelper.h"

#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#import <AFHTTPSessionManager.h>

#import "HQBaseRequestSDKSetting.h"

 
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>


@interface IPHelper ()

@property (nonatomic, strong) AFHTTPSessionManager* manager;

@end

@implementation IPHelper

+ (IPHelper *)shareInstance
{
    static IPHelper* helper;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        helper = [[IPHelper alloc] init];
    });
    return helper;
}

//获取URL的IP地址
+ (NSString *)getIPAddressForHostString:(NSString *) theHost
{
    if (!theHost) {
        return @"can't get IP!";
    }
    
    char **pptr;
    struct hostent *hptr;
    char str[32];
    /*　判断是否是IP地址,如果已经是IP地址了,直接返回theHost*/
    if (inet_addr([theHost UTF8String]) == 0) {
        return theHost;
    }
    /* 取得命令后第一个参数，即要解析的域名或主机名 */
    //ptr = *[theHost UTF8String];
    /* 调用gethostbyname()。调用结果都存在hptr中 */
    if ((hptr = gethostbyname([theHost UTF8String])) == NULL) {
        //         printf("gethostbyname error for host:%s\n", [theHost UTF8String]);
        return nil; /* 如果调用gethostbyname发生错误，返回1 */
    }
    /* 将主机的规范名打出来 */
//         printf("official hostname:%s\n",hptr->h_name);
    /* 主机可能有多个别名，将所有别名分别打出来 */
//         for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
//             printf(" alias:%s\n",*pptr);
    
    NSString *addressString;
    /* 根据地址类型，将地址打出来 */
    switch (hptr->h_addrtype) {
        case AF_INET:
        case AF_INET6:
            pptr=hptr->h_addr_list;
            addressString = [NSString stringWithCString:inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)) encoding:NSUTF8StringEncoding];
//            NSLog(@"address = %@",addressString);
            /* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */
            //         for(;*pptr!=NULL;pptr++)
            //             printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
            break;
        default:
            printf("unknown address type\n");
            break;
    }   
    return addressString;   
}

- (NSString *)ip
{
    if (!_ip) {
        _ip = [[self class] getIPAddress];
    }
    return _ip;
}

- (NSString *)queryIpInfo
{
    NSString * ip = [[self class] getIPAddress];
    self.ip = ip;
    return ip;
//    [self.manager GET:ipCheckUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        @try {
//            NSDictionary *dict = responseObject;
//            NSNumber *code = dict[@"code"];
//            if (code && code.intValue == 0) {
//                self->_city = [NSString stringWithFormat:@"%@", dict[@"data"][@"city"]];
//                self->_isp = [NSString stringWithFormat:@"%@", dict[@"data"][@"isp"]];
//                self->_ip = [NSString stringWithFormat:@"%@", dict[@"data"][@"ip"]];
//
//                DDLogInfo(@"<IPHelper>ip info (%@|%@|%@)", self.city, self.isp, self.ip);
//            }
//        } @catch (NSException *exception) {
//            DDLogError(@"<IPHelper> exp %@", exception);
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DDLogInfo(@"<IPHelper> get ip info fail,error=%@",error);
//    }];
}

+ (NSString *)getIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
//                if ([name isEqualToString:@"en0"]){ // Wi-Fi adapter
//                    NSLog(@"IP:%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]);
//                }
               
                NSString * ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                
                ip = ip ? ip :@"";
                NSLog(@"networkname= %@- ip=  %@",name,ip);
                return ip ;
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return @"";
}


- (NSString *)ipInfo
{
    return [NSString stringWithFormat:@"%@|%@|%@", self.city, self.isp, self.ip];
}

- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    }
    return _manager;
}
@end
